<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="派工号" prop="docNum">
        <el-input
          v-model="queryParams.docNum"
          placeholder="请输入派工号模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="queryParams.dtDocStart"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="起始日期"
          end-placeholder="截止日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.dtDocFinish"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="起始日期"
          end-placeholder="截止日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:done:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:done:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:done:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:done:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doneList" :highlight-current-row="true" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.actualNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ props.row.confirmNickName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="汇报时间" align="center" prop="docDt" width="150"/>


      <el-table-column label="汇报号" align="center" prop="docNum" width="150" />

      <el-table-column label="工序类型" align="center" prop="mesDictProcessType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_dict_process_type" :value="scope.row.mesDictProcessType"/>
        </template>
      </el-table-column>

      <el-table-column label="工序名称" align="center" prop="mesDictProcessName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_dict_process_name" :value="scope.row.mesDictProcessName"/>
        </template>
      </el-table-column>

      <el-table-column label="工序内容" align="center" prop="processContent" width="120" :show-overflow-tooltip="true"/>

      <el-table-column label="工序符号" align="center" prop="mesDictProcessCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_dict_process_code" :value="scope.row.mesDictProcessCode"/>
        </template>
      </el-table-column>

      <el-table-column label="物料名称" align="center" prop="itemName" width="180px" :show-overflow-tooltip="true" />
      <el-table-column label="物料编码" align="center" prop="itemNum" width="180px" :show-overflow-tooltip="true" />
      <el-table-column label="规格" align="center" prop="itemSpecification" width="120px"/>

      <el-table-column label="完工数量" align="center" prop="doneQty" />

      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
        </template>
      </el-table-column>

      <el-table-column label="开始日期" align="center" prop="dtStart" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dtStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="dtDone" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dtDone, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="汇报人" align="center" prop="attentionUserName" width="150px"/>

      <el-table-column label="加工号" align="center" prop="workDocNum" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="show_work(scope.row)"
          >{{scope.row.workDocNum}}<i class="el-icon-caret-right"></i>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="标准定额" align="center" prop="doneQuotaWorkingHours" width="120" />
      <el-table-column label="汇报定额" align="center" prop="totalQuotaWorkingHours" width="120" />
      <el-table-column label="实作时长(分)" align="center" prop="totalWorkingHours" width="120" />

      <el-table-column label="需质检" align="center" prop="sysYesNoQc">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoQc"/>
        </template>
      </el-table-column>

      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:done:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:done:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'">删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_confirm(scope.row)"
            v-hasPermi="['oa:confirm:edit']"
            :disabled="scope.row.oaDictConfirmStatus !='waiting'"> 审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_qc(scope.row)"
            v-hasPermi="['qms:qc:add']"
            :disabled=" scope.row.oaDictConfirmStatus != 'pass'"
            v-show="scope.row.sysYesNoQc == 'Y'"
          > 质检
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改完工汇报对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 工序汇报 -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">

          <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                    style="margin-bottom: 15px;"
                    :title="form.latestTaskInfo"
                    type="info"
                    :closable="false"
                    effect="dark"
          >
          </el-alert>
          <div slot="header" class="clearfix">
            <span><b>完工汇报</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
              <el-switch
                v-model="fold_form_to_done"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>
          <div v-show="fold_form_to_done=='false'">
            <el-row>

              <el-col :span="12">
                <el-form-item label="加工单" prop="fkMesWorkUuid" >
                  <el-input v-model="form.fkMesWorkUuid"  v-show="false"/>
                  <el-input placeholder="请点击右侧按钮选择加工单"
                            v-model="form.selectedWork"
                            class="input-with-select"
                            :style="{width: '100%'}"
                  >
                    <el-button type="info" plain
                               @click="dialog_show_selectWork"
                               slot="append"
                               icon="el-icon-search"

                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="quotaQtyMin">
                  <span slot="label">
                    标准定额
                   <el-tooltip content="工艺施工中的定额（单位：分钟）只读" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>

                  <el-input placeholder="请先选择工序" v-model="form.quotaQtyMin" readOnly>
                    <template slot="append">分钟</template>
                  </el-input>

                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="完工数量" prop="doneQty">
                  <el-input-number v-model="form.doneQty"  placeholder="请输入完工数量"
                                   :style="{width: '100%'}" @input="inputChange"/>
                </el-form-item>
              </el-col>


              <el-col :span="12">
                <el-form-item label="汇报号" prop="docNum">
                  <el-input v-model="form.docNum" placeholder="请输入汇报号" :style="{width: '100%'}" />
                </el-form-item>
              </el-col>



              <el-col :span="12">
                <el-form-item label="开始时间" prop="dtStart">
                  <el-date-picker clearable
                                  v-model="form.dtStart"
                                  type="datetime"
                                  placeholder="选择开始时间"
                                  :style="{width: '100%'}">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="dtDone">
                  <el-date-picker clearable
                                  v-model="form.dtDone"
                                  type="datetime"
                                  placeholder="选择结束时间"
                                  :style="{width: '100%'}">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="汇报人" prop="fkUserId">
                  <el-input v-model="form.fkUserId" v-show="false"/>
                  <el-input placeholder="请点击右侧按钮选择汇报人" readOnly="true" v-model="form.attentionUserName"
                            class="input-with-select"  >
                    <el-button @click="showDialog_selectAttentionUser(form)" slot="append" icon="el-icon-search"
                               :style="{width: '100%'}"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="汇报时间" prop="docDtDone">
                  <el-date-picker clearable
                                  v-model="form.docDtDone"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm"
                                  placeholder="选择汇报时间"
                                  :style="{width: '100%'}"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="totalQuotaQtyMin">
                  <span slot="label">
                    总定额
                   <el-tooltip content="总定额：单位定额*数量，不用填写，自动带出" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>

                  <el-input placeholder="请先选择工序" v-model="form.totalQuotaQtyMin" readOnly>
                    <template slot="append">分钟</template>
                  </el-input>

                </el-form-item>
              </el-col>


            </el-row>
          </div>
        </el-card>

        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>生产员工</b></span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddMesJobDoneWorkers"
              >添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteMesJobDoneWorkers"
              >删除</el-button>
            </el-col>
          </el-row>

          <el-table :data="mesJobDoneWorkersList" :row-class-name="rowMesJobDoneWorkersIndex" @selection-change="handleMesJobDoneWorkersSelectionChange" ref="mesJobDoneWorkers">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="排序序号" prop="orderNum"  align="center" width="">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderNum" placeholder="请输入排序序号" />
              </template>
            </el-table-column>

            <el-table-column label="员工姓名" prop="fkUserIdWorker"  align="center" width="240">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fkUserIdWorker" v-show="false"/>
                <el-input placeholder="请选择员工" v-model="scope.row.workerName"
                          class="input-with-select" >
                  <el-button @click="showDialog_selectWorker(scope)" slot="append" icon="el-icon-search" ></el-button>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="定额工时" prop="quotaWorkingHours"  align="center" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.quotaWorkingHours" placeholder="请输入定额工时" />
              </template>
            </el-table-column>

            <el-table-column label="实作工时(m)" prop="workingHours"  align="center" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.workingHours" placeholder="请输入实作工时" />
              </template>
            </el-table-column>
          </el-table>


        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--质量检查-->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title_qc" :visible.sync="open_qc" width="800px" append-to-body :close-on-click-modal=false>
      <el-form ref="form_qc" :model="form_qc"  label-width="100px">

        <el-input v-model="form_qc.fkJobDoneUuid" v-show="false"/>

          <el-row>

            <el-col :span="12">
              <el-form-item label="质检号" prop="docNum">
                <el-input v-model="form_qc.docNum"

                          placeholder="请输入质检号"
                          clearable filterable
                          :style="{width: '100%'}" @blur="trimOnBlur"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="质检时间" prop="docDt">
                <el-date-picker clearable size="small"
                                v-model="form_qc.docDt"
                                type="datetime"
                                placeholder="选择质检时间"
                                value-format="yyyy-MM-dd HH:mm"
                                :style="{width: '100%'}" clearable filterable>
                </el-date-picker>
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item label="检查数量" prop="qcQuantity">
                <el-input-number v-model="form_qc.qcQuantity"

                                 clearable filterable
                                 placeholder="请输入检查数量"
                                 :style="{width: '100%'}"
                                 @blur="trimOnBlur"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="不合格数量" prop="failQuantity">
                <el-input-number v-model="form_qc.failQuantity"
                                 clearable
                                 filterable placeholder="请输入不合格数量"
                                 :style="{width: '100%'}"
                                 @blur="trimOnBlur"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合格数量" prop="qcPassQty">
                <el-input-number v-model="form_qc.qcPassQty"
                                 clearable
                                 filterable placeholder="请输入合格数量"
                                 :style="{width: '100%'}"
                                 @blur="trimOnBlur"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="超差品数量" prop="poorQty">
                <el-input-number v-model="form_qc.poorQty"
                                 clearable
                                 filterable placeholder="请输入超差品数量"
                                 :style="{width: '100%'}"
                                 @blur="trimOnBlur"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="废品数量" prop="wasteQty">
                <el-input-number v-model="form_qc.wasteQty"
                                 clearable
                                 filterable placeholder="请输入废品数量"
                                 :style="{width: '100%'}"
                                 @blur="trimOnBlur"/>
              </el-form-item>
            </el-col>


            <el-col :span="12">

              <el-form-item label="质检员" prop="fkAttentionUserId">
                <el-input v-model="form_qc.fkAttentionUserId" v-show="false"/>
                <el-input placeholder="请点击右侧按钮选择质检员" readOnly="true" v-model="form_qc.qcUserName"
                          class="input-with-select">
                  <el-button @click="showDialog_selectQc" slot="append" icon="el-icon-search"
                  ></el-button>
                </el-input>
              </el-form-item>

            </el-col>


            <el-col :span="24">
              <el-form-item label="备注" prop="qcNote">
                <el-input v-model="form_qc.qcNote" type="textarea" @blur="trimOnBlur"
                          autosize clearable filterable
                          placeholder="请输入备注" :style="{width: '100%'}" maxlength="50"
                          show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_qc">确 定</el-button>
        <el-button @click="cancel_qc">取 消</el-button>
      </div>
    </el-dialog>


    <select-user ref="component_selectAttentionUser" @ok="selectAttentionUser_done" />
    <select-user ref="component_selectWorker" @ok="selectWorker_done" />
    <select-user ref="component_selectQc" @ok="selectQc_done"/>

    <select-Work ref="component_selectWork" @ok="selectWork_done"/>
    <confirm ref="component_confirm" @ok="confirm_done"/>
  </div>
</template>

<script>

import { listDone, getDone, delDone, addDone, updateDone } from "@/api/mes/done";
import selectUser from "../../comn/userGroup/selectUser";
import {newDocNum} from "@/api/oa/docNum";
import { parseTime } from '@/utils/ruoyi'
import selectWork from "../../mes/work/selectWork";
import confirm from "../../oa/confirm";
import {  getWork } from "@/api/mes/work";
import { addQc} from "@/api/qms/qc";
import {  addWaste } from "@/api/qms/waste";
import {trimOnBlur} from '@/utils/form'

export default {
  dicts: ['sys_normal_disable', 'mes_dict_process_type', 'mes_dict_process_name',
    'mes_dict_process_code', 'sys_yes_no', 'wms_dict_measuring_unit','oa_dict_confirm_status'],
  name: "Done",
  components: { selectUser,selectWork,confirm },
  data() {

    let validateDtStart = (rule, value, callback) => {
      if (!value) {
        callback(new Error("开始日期不能为空"));
      } else {
        // 如果结束日期没选
        if (!this.form.dtDone) {
          callback();
        } else {
          // 结束日期有进行判断
          if (this.compareDate(value, this.form.dtDone)) {
            // 如果开始日期在结束日期之前
            callback();
          } else {
            callback(new Error("开始日期不能再结束日期之后，请重新选择"));
          }
        }
      }
    };
    let validateDtEnd = (rule, value, callback) => {
      if (!value) {
        callback(new Error("结束日期不能为空"));
      } else {
        if (!this.form.dtStart) {
          callback();
        } else {
          // 开始日期有
          if (this.compareDate(this.form.dtStart, value)) {
            callback();
          } else {
            callback(new Error("结束日期不能在开始日期前，请重新选择"));
          }
        }
      }
    };
    return {
      fold_form_to_done: 'false',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMesJobDoneWorkers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 完工汇报表格数据
      doneList: [],
      // 完工汇报（工人、工时）表格数据
      mesJobDoneWorkersList: [],
      // 弹出层标题
      title: "",
      title_qc: "",
      // 是否显示弹出层
      open: false,
      open_qc: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fkMesWorkUuid: null,
        fkDeptId: null,
        fkUserId: null,
        fkUserIdQc: null,
        dtStart: null,
        dtDone: null,
        doneQty: null,
        actualNote: null,
        docDt: null,
        oaDictConfirmStatus: null,
        fkConfirmUserId: null,
        confirmDt: null,
        confirmNote: null
      },
      // 表单参数
       form: {},
      form_qc: {},
      // 表单校验
      rules: {
        fkMesWorkUuid: [
          { required: true, message: "加工单不能为空", trigger: "change" }
        ],
        doneQty: [
          { required: true, message: "数量不能为空", trigger: "change" }
        ],
        docNum: [
          { required: true, message: "汇报号不能为空", trigger: "change" }
        ],
        dtStart: [
          {
            trigger: ["change"],
            validator: validateDtStart,
          },
        ],
        dtDone: [
          {
            trigger: ["change"],
            validator: validateDtEnd,
          },
        ],
        fkUserId: [
          { required: true, message: "汇报人不能为空", trigger: "change" }
        ],
        fkUserIdQc: [
          { required: true, message: "质检员不能为空", trigger: "change" }
        ],
        docDt: [
          { required: true, message: "汇报时间不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {


    // $route params
    let doneDocNum = this.$route.params && this.$route.params.doneDocNum;
    if (doneDocNum) {
      this.queryParams.docNum = doneDocNum
    }else console.log('！！！ 无参数 ！！！')

    this.getList();
  },
  methods: {
    // 比较两个日期
    compareDate(start, end) {
      return new Date(end).getTime() >= new Date(start).getTime();
    },
    trimOnBlur,
    inputChange(){
      if(this.form.quotaQtyMin == "请先选择加工单"){
        this.form.quotaQtyMin=0
      }
      this.form.totalQuotaQtyMin=this.form.doneQty*this.form.quotaQtyMin
    },

    /** 打开对话框：审核 */
    showDialog_confirm(row) {
      console.log(row)
      let obj = {
        tableName: 'mes_job_done',
        uuidColumn: 'job_done_uuid',
        fkUuid: row.jobDoneUuid,
        attentionUserNickName: row.attentionUserName,
        oaDictConfirmStatus: row.oaDictConfirmStatus,
        msg: `请审核完工汇报单, 汇报号：${row.docNum}`
      }
      this.$refs.component_confirm.showDialog_confirm(obj);

    },

    confirm_done() {

      this.getList()
    },
    /** 查询完工汇报列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.dtDocStart) {
        this.queryParams.dtDocStartBegin = this.queryParams.dtDocStart[0]
        this.queryParams.dtDocStartEnd = this.queryParams.dtDocStart[1]
      } else {
        this.queryParams.dtDocStartBegin = null
        this.queryParams.dtDocStartEnd = null
      }
      if (this.queryParams.dtDocFinish) {
        this.queryParams.dtDocFinishBegin = this.queryParams.dtDocFinish[0]
        this.queryParams.dtDocFinishEnd = this.queryParams.dtDocFinish[1]
      } else {
        this.queryParams.dtDocFinishBegin = null
        this.queryParams.dtDocFinishEnd = null
      }
      listDone(this.queryParams).then(response => {
        this.doneList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },  // 取消按钮
    cancel_qc() {
      this.open_qc = false;
      this.reset_qc();
    },
    // 表单重置
    reset() {
      this.form = {
        jobDoneUuid: null,
        fkMesWorkUuid: null,
        fkDeptId: null,
        fkUserId: null,
        fkUserIdQc: null,
        dtStart: null,
        dtDone: null,
        docNum: null,
        actualNote: null,
        docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
        docDtDone: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
        oaDictConfirmStatus: "0",
        doneQty: null,
        fkConfirmUserId: null,
        confirmDt: null,
        confirmNote: null,
        attentionUserName: null,
        selectedWork: null,
        quotaQtyMin: '请先选择加工单',
      };
      this.mesJobDoneWorkersList = [];
      this.resetForm("form");
    },

    reset_qc() {
      this.form_qc = {
        docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
        docNum:null,
        qcUserName:null,
        fkAttentionUserId:null,
        failQuantity:null,
        poorQty:null,
        wasteQty:null,
      };
      this.resetForm("form_qc");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobDoneUuid)
      this.docDts = selection.map(item => item.docDt)
      this.docNums = selection.map(item => item.docNum)
      this.single = selection.length!==1
      this.oaDictConfirmStatus = selection.map(i=>i.oaDictConfirmStatus)
      //批量删除判断选中的数据中是否含有待审或已经审核的数据，只有选中的数据全为编辑中状态时，批量删除按钮才生效
      this.multiple=
        (this.oaDictConfirmStatus.indexOf('editing')>-1 && [...new Set(this.oaDictConfirmStatus)]=='editing') ? false : true
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.oaDictConfirmStatus='editing'

      newDocNum({preCode: 'DON-', len: 12}).then(response => {
        this.form.docNum = response.msg
        console.log(this.form.docNum)

      })

      this.open = true;
      this.title = "添加完工汇报";
    },

    submitForm_qc() {
      console.log(this.form_qc)
      this.$refs["form_qc"].validate(valid => {
        if (valid) {
            addQc(this.form_qc).then(response => {
              this.$modal.msgSuccess("质检成功");
              console.log(this.form_qc.wasteQty)
              if(this.form_qc.wasteQty != 0){
                addWaste(this.form_qc).then(response => {
                });
              }
              this.open_qc = false;
            });
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const jobDoneUuid = row.jobDoneUuid || this.ids
      getDone(jobDoneUuid).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.form.docDtDone = this.form.docDt
        this.form.selectedWork =` 加工单号：${this.form.workDocNum}`
        this.form.attentionUserName = this.form.jobDoneUserName
        this.mesJobDoneWorkersList = response.data.mesJobDoneWorkersList;
        console.log(this.mesJobDoneWorkersList)

        this.form.oaDictConfirmStatus =
          ('editing' == this.form.oaDictConfirmStatus || 'reject' == this.form.oaDictConfirmStatus)
            ? 'editing' : this.form.oaDictConfirmStatus


        if(row.oaDictConfirmStatus!='editing'||row.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
          this.form.latestTaskInfo='💡 该条记录审核状态为'+
            this.selectDictLabel(this.dict.type.oa_dict_confirm_status, row.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
        }

        this.open = true;
        this.title = "修改完工汇报";
      });
    },

    /** 下达按钮操作 */
    showDialog_qc(row) {
      this.reset_qc()
      this.form_qc.fkJobDoneUuid = row.jobDoneUuid

      this.form_qc.qcPassQty = row.doneQty

      newDocNum({preCode: 'QMS-', len: 12}).then(response => {
        this.form_qc.docNum = response.msg
      })
      this.open_qc = true;
      this.title_qc = "质量检查（新增质检单）";
    },
    /** 提交按钮 */
    submitForm(confirmStatus) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
          this.form.mesJobDoneWorkersList = this.mesJobDoneWorkersList;
          if (this.form.jobDoneUuid != null) {
            updateDone(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDone(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jobDoneUuids = row.jobDoneUuid || this.ids;
      const docDts = row.docDt || this.docDts;
      const docNums = row.docNum || this.docNums;
      this.$modal.confirm('是否确认删除汇报时间为"' + docDts + '",汇报号为"'+docNums+'"的完工单？','删除确认').then(function() {
        return delDone(jobDoneUuids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 完工汇报（工人、工时）序号 */
    rowMesJobDoneWorkersIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 完工汇报（工人、工时）添加按钮操作 */
    handleAddMesJobDoneWorkers() {
      let obj = {};
      obj.orderNum = "";
      obj.fkUserIdWorker = "";
      obj.quotaWorkingHours = "";
      obj.workingHours = "";
      obj.workerName = "";
      this.mesJobDoneWorkersList.push(obj);
    },
    /** 完工汇报（工人、工时）删除按钮操作 */
    handleDeleteMesJobDoneWorkers() {
      if (this.checkedMesJobDoneWorkers.length == 0) {
        this.$modal.msgError("请先选择要删除的完工汇报（工人、工时）数据");
      } else {
        const mesJobDoneWorkersList = this.mesJobDoneWorkersList;
        const checkedMesJobDoneWorkers = this.checkedMesJobDoneWorkers;
        this.mesJobDoneWorkersList = mesJobDoneWorkersList.filter(function(item) {
          return checkedMesJobDoneWorkers.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleMesJobDoneWorkersSelectionChange(selection) {
      this.checkedMesJobDoneWorkers = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/done/export', {
        ...this.queryParams
      }, `mes_done.xlsx`)
    },

    /** 显示对话框：选择加工单 */
    dialog_show_selectWork() {
      this.$refs.component_selectWork.dialog_show_selectWork();
    },

    /** 选择加工单完成 */
    selectWork_done(plan) {
      this.form.fkMesWorkUuid = plan.mesWorkUuid
      console.log(plan)
      this.form.selectedWork =
        `加工单号：${plan.docNum}，单据时间：${plan.docDt}`
      this.form.quotaQtyMin = plan.quotaWorkingHours
      this.form.mesWorkUuid = plan.mesWorkUuid
      console.log(this.form.mesWorkUuid)
      getWork(this.form.mesWorkUuid).then(response => {
        console.log(response)
        this.mesJobDoneWorkersList = response.data.mesWorkWorkersList;
      });
    },

    /** 选择经办人 */
    showDialog_selectQc() {
      this.$refs.component_selectQc.userGroup = 'quality_checker';
      this.$refs.component_selectQc.show();
    },
    /** 选择经办人 - 完成 */
    selectQc_done(user) {
      this.form_qc.fkAttentionUserId = user.userId
      this.form_qc.qcUserName = user.userNickNameAndId
    },

    /** 选择经办人 */
    showDialog_selectAttentionUser( form ) {
      this.currentForm = form
      this.$refs.component_selectAttentionUser.userGroup = 'worker';
      this.$refs.component_selectAttentionUser.show();
    },

    /** 显示对话框：选择工人 */
    showDialog_selectWorker(scope) {
      this.currRowScope = scope
      this.$refs.component_selectWorker.userGroup = 'worker';
      this.$refs.component_selectWorker.show();
    },

    /** 选择经办人 - 完成 */
    selectAttentionUser_done(user) {
      this.currentForm.fkUserId = user.userId
      this.currentForm.attentionUserName = user.userNickNameAndId
    },

    /** 选择工人 - 完成 */
    selectWorker_done(user) {
      this.currRowScope.row.fkUserIdWorker = user.userId
      this.currRowScope.row.workerName = user.userNickNameAndId
    },



    // 显示 - 加工号
    show_work(r) {
      console.log(r)
      this.$router.push(`/mes/work/docNum/${r.workDocNum}`);
    },

  }
};
</script>
